package com.cc.moxingvoice.lock;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.MotionEvent;
import android.view.View;

import com.cc.moxingvoice.R;
import com.cc.moxingvoice.base.BaseActivity;
import com.cc.moxingvoice.base.BaseLock;
import com.cc.moxingvoice.constant.LocalPath;
import com.cc.moxingvoice.databinding.ActivityMainBinding;
import com.cc.moxingvoice.ui.main.FindFragment;
import com.cc.moxingvoice.ui.main.ForumFragment;
import com.cc.moxingvoice.ui.main.MainActivity;
import com.cc.moxingvoice.ui.main.MineFragment;
import com.cc.moxingvoice.ui.main.VoicePackageFragment;
import com.cc.moxingvoice.ui.window.FloatWindowService;
import com.cc.moxingvoice.ui.window.MyWindowManager;
import com.cc.moxingvoice.utils.AssetsUtil;
import com.cc.moxingvoice.utils.CheckUpdateUtil;
import com.cc.moxingvoice.utils.PermissionsUtil;
import com.cc.moxingvoice.utils.FilesUtil;
import com.cc.moxingvoice.utils.ShareUtil;
import com.cc.moxingvoice.widget.dialog.ButtonTwoDialog;
import com.cc.moxingvoice.widget.dialog.LoadDialog;
import com.mob.analysdk.AnalySDK;
import com.superc.cframework.utils.SPUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import ezy.assist.compat.RomUtil;
import ezy.assist.compat.SettingsCompat;

/**
 * 创建日期：2018/2/23 on 14:41
 * 描述：
 * 作者：郭士超
 * QQ：1169380200
 */

public class MainLock extends BaseLock<ActivityMainBinding> {

    private List<Fragment> mFragmentList;
    private VoicePackageFragment mVoicePackageFragment;
    private FindFragment mFindFragment;
    private ForumFragment mForumFragment;
    private MineFragment mMineFragment;

    private boolean startTypeShow;
    private boolean flagForum;

    public MainLock(Context context, ActivityMainBinding binding) {
        super(context, binding);
    }

    public MainLock(Context context, ActivityMainBinding binding, Bundle bundle) {
        super(context, binding, bundle);
    }

    @Override
    protected void init() {
        agreeProtocol();

        CheckUpdateUtil.checkUpdate(getContext(), false);

        mobAnalysis();

        initFragment();

        if (PermissionsUtil.verifyStoragePermissions(((BaseActivity) getContext()))) {
            if (SPUtil.get(getContext(), "first_open", true)) {
                mobVersion();

                new CopyFile().execute();
                return;
            }

            afterPermissions();
        }
    }

    private void initFragment() {
        mBinding.llStartType.setVisibility(View.GONE);

        mFragmentList = new ArrayList<>();
        mVoicePackageFragment = new VoicePackageFragment();
        mFindFragment = new FindFragment();
        mForumFragment = new ForumFragment();
        mMineFragment = new MineFragment();
        mFragmentList.add(mVoicePackageFragment);
        mFragmentList.add(mFindFragment);
        mFragmentList.add(mForumFragment);
        mFragmentList.add(mMineFragment);

        voicePage(null);
    }

    public void startGame(View view) {
        MyWindowManager.setStartType(MyWindowManager.GAME);
        startFloatWindowService();
    }

    public void startQQ(View view) {
        MyWindowManager.setStartType(MyWindowManager.QQ);
        startFloatWindowService();
    }

    public void startWX(View view) {
        MyWindowManager.setStartType(MyWindowManager.WX);
        startFloatWindowService();
    }

    private void startFloatWindowService() {
        mBinding.llStartType.setVisibility(View.GONE);
        startTypeShow = false;
        mBinding.tvStart.setText(R.string.start);

        if (MyWindowManager.showControlWindow) {
            return;
        }
        Intent startIntent = new Intent(getContext(), FloatWindowService.class);
        getContext().startService(startIntent);
    }

    public void hideStartType() {
        if (startTypeShow) {
            mBinding.llStartType.setVisibility(View.GONE);
            startTypeShow = false;
            mBinding.tvStart.setText(R.string.start);
        }
    }

    /**
     * 打开启动方式
     *
     * @param view
     */
    public void start(View view) {
        // 检测悬浮窗权限
        if (SettingsCompat.canDrawOverlays(getContext())) {
            if (!(SPUtil.get(getContext(), "share", false) || ShareUtil.share)) {
                showToast(getContext().getString(R.string.share_privileges));
                ShareUtil.showShare(getContext());
                return;
            }
            // 显示启动按钮
            if (startTypeShow) {
                mBinding.llStartType.setVisibility(View.GONE);
                mBinding.tvStart.setText(R.string.start);
            } else {
                mBinding.llStartType.setVisibility(View.VISIBLE);
                mBinding.tvStart.setText(R.string.cancel);
            }
            startTypeShow = !startTypeShow;
        } else {
            showToast("我需要您手动打开悬浮窗权限才可使用");
            if (RomUtil.isMiui()) {
                PermissionsUtil.showFloatWindow(getContext());
                return;
            }
            // 跳转到悬浮窗权限设置页
            SettingsCompat.manageDrawOverlays(getContext());
        }
    }

    public void voicePage(View view) {
        ((MainActivity) mContext).displayFragment(mFragmentList, mVoicePackageFragment, ((MainActivity) mContext).getSupportFragmentManager(), R.id.main_ll);
        initRadioGroup();
        Drawable home = getContext().getResources().getDrawable(R.drawable.home_page2);
        mBinding.mainVoice.setCompoundDrawablesRelativeWithIntrinsicBounds(null, home, null, null);
        mBinding.mainVoice.setTextColor(getContext().getResources().getColor(R.color.main_color));
    }

    public void findPage(View view) {
        ((MainActivity) mContext).displayFragment(mFragmentList, mFindFragment, ((MainActivity) mContext).getSupportFragmentManager(), R.id.main_ll);
        initRadioGroup();
        Drawable find = getContext().getResources().getDrawable(R.drawable.find_page2);
        mBinding.mainFind.setCompoundDrawablesRelativeWithIntrinsicBounds(null, find, null, null);
        mBinding.mainFind.setTextColor(getContext().getResources().getColor(R.color.main_color));
    }

    public void forumPage(View view) {
        ((MainActivity) mContext).displayFragment(mFragmentList, mForumFragment, ((MainActivity) mContext).getSupportFragmentManager(), R.id.main_ll);
        initRadioGroup();
        Drawable forum = getContext().getResources().getDrawable(R.drawable.forum_page2);
        mBinding.mainForum.setCompoundDrawablesRelativeWithIntrinsicBounds(null, forum, null, null);
        mBinding.mainForum.setTextColor(getContext().getResources().getColor(R.color.main_color));
        flagForum = true;
    }

    public void minePage(View view) {
        ((MainActivity) mContext).displayFragment(mFragmentList, mMineFragment, ((MainActivity) mContext).getSupportFragmentManager(), R.id.main_ll);
        initRadioGroup();
        Drawable mine = getContext().getResources().getDrawable(R.drawable.mine_page2);
        mBinding.mainMine.setCompoundDrawablesRelativeWithIntrinsicBounds(null, mine, null, null);
        mBinding.mainMine.setTextColor(getContext().getResources().getColor(R.color.main_color));
    }

    private void initRadioGroup(){
        Drawable home = getContext().getResources().getDrawable(R.drawable.home_page1);
        mBinding.mainVoice.setCompoundDrawablesRelativeWithIntrinsicBounds(null, home, null, null);
        mBinding.mainVoice.setTextColor(getContext().getResources().getColor(R.color.gray_70));

        Drawable find = getContext().getResources().getDrawable(R.drawable.find_page1);
        mBinding.mainFind.setCompoundDrawablesRelativeWithIntrinsicBounds(null, find, null, null);
        mBinding.mainFind.setTextColor(getContext().getResources().getColor(R.color.gray_70));

        Drawable forum = getContext().getResources().getDrawable(R.drawable.forum_page1);
        mBinding.mainForum.setCompoundDrawablesRelativeWithIntrinsicBounds(null, forum, null, null);
        mBinding.mainForum.setTextColor(getContext().getResources().getColor(R.color.gray_70));

        Drawable mine = getContext().getResources().getDrawable(R.drawable.mine_page1);
        mBinding.mainMine.setCompoundDrawablesRelativeWithIntrinsicBounds(null, mine, null, null);
        mBinding.mainMine.setTextColor(getContext().getResources().getColor(R.color.gray_70));

        flagForum = false;
    }

    private void afterPermissions() {
        //有权限
        FilesUtil.mkdirPath(LocalPath.VOICE_PATH);
        FilesUtil.saveSharePic(getContext(), LocalPath.APP_PATH, LocalPath.SHARE_PIC);
        voicePackageRefreshList();
    }

    public void voicePackageRefreshList(){
        mVoicePackageFragment.refreshList();
    }

    public void onRequestPermissionsResult(boolean result) {
        if (result) {
            if (SPUtil.get(getContext(), "first_open", true)) {
                mobVersion();

                new CopyFile().execute();
                return;
            }

            afterPermissions();
        } else {
            showToast("您需要给我读写权限才可使用，您刚才拒绝了权限");
        }
    }

    // 同意协议
    private void agreeProtocol() {
        if (SPUtil.get(getContext(), "agree_protocol", false)) {
            return;
        }
        new ButtonTwoDialog(mContext, R.style.dialog, mContext.getString(R.string.protocol), new ButtonTwoDialog.OnCloseListener() {
            @Override
            public void onClick(Dialog dialog, boolean confirm) {
                if (confirm) {
                    SPUtil.put(getContext(), "agree_protocol", true);
                    dialog.dismiss();
                } else {
                    finish();
                }
            }
        }).setTitle(mContext.getString(R.string.protocol_title)).setPositiveButton(mContext.getString(R.string.agree)).show();
    }

    private void mobVersion() {
        try {
            String versionName = "";
            PackageInfo packageInfo = getContext().getPackageManager()
                    .getPackageInfo(getContext().getPackageName(),
                            PackageManager.GET_CONFIGURATIONS);
            versionName = packageInfo.versionName;
            HashMap<String, Object> eventParams = new HashMap<String, Object>();
            eventParams.put("versionName", versionName);
            AnalySDK.trackEvent("version", eventParams);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }

    private void mobAnalysis() {
        // 统计事件名称和触发次数
//        AnalySDK.trackEvent(eventName);
        // 以携带参数的方式统计事件名称和触发次数，其中的eventParams是一个Map或者Json
//        AnalySDK.trackEvent(eventName, eventParams);

        HashMap<String, Object> eventParams = new HashMap<String, Object>();
        eventParams.put("page", "Main Page");
        AnalySDK.trackEvent("page-jump", eventParams);
    }

    public boolean onHttpBack() {
        if (flagForum){
            if (mForumFragment.httpBack()){
                return true;
            }
        }
        return false;
    }

    class CopyFile extends AsyncTask<String, String, String> {

        @Override
        protected void onPreExecute() {
            LoadDialog.show(getContext(), "正在解压资源");
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... params) {
            // 复制资源
            AssetsUtil.copyAssets(getContext(), LocalPath.ASSETS_VOICE_PATH, LocalPath.VOICE_PATH);
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub
            LoadDialog.dismiss(getContext());

            SPUtil.put(getContext(), "first_open", false);
            Runtime.getRuntime().gc();

            afterPermissions();
        }

    }

}
